package com.xhs.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhs.dto.TaskListResponse;
import com.xhs.model.SearchTask;
import com.xhs.mapper.SearchTaskMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 搜索任务数据库操作Manager
 *
 * @author xhs
 */
@Service
public class SearchTaskManager extends ServiceImpl<SearchTaskMapper, SearchTask> {

    /**
     * 根据用户ID查询任务列表
     *
     * @param userId 用户ID
     * @return 任务列表
     */
    public List<SearchTask> findByUserId(Long userId) {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getDeleted, 0)
                .orderByDesc(SearchTask::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 根据手机号查询任务列表
     *
     * @param phoneNumber 手机号
     * @return 任务列表
     */
    public List<SearchTask> findByPhoneNumber(String phoneNumber) {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getPhoneNumber, phoneNumber)
                .eq(SearchTask::getDeleted, 0)
                .orderByDesc(SearchTask::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 分页查询任务列表
     *
     * @param userId   用户ID
     * @param pageNum  页码
     * @param pageSize 页大小
     * @return 分页结果
     */
    public IPage<SearchTask> findByUserIdWithPage(Long userId, int pageNum, int pageSize) {
        Page<SearchTask> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getDeleted, 0)
                .orderByDesc(SearchTask::getCreateTime);
        return this.page(page, queryWrapper);
    }



    /**
     * 创建任务
     *
     * @param searchTask 任务信息
     * @return 是否成功
     */
    public boolean createTask(SearchTask searchTask) {
        searchTask.setCreateTime(LocalDateTime.now());
        searchTask.setUpdateTime(LocalDateTime.now());
        searchTask.setDeleted(0);
        return this.save(searchTask);
    }

    /**
     * 更新任务状态
     *
     * @param id 任务ID
     * @param status 状态
     */
    public void updateTaskStatus(Long id, String status) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, id)
                .set(SearchTask::getStatus, status)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 更新任务执行进度
     *
     * @param id               任务ID
     * @param totalQrCodes         总二维码数
     */
    public void updateTaskProgress(Long id, Integer totalQrCodes) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, id)
                .set(SearchTask::getTotalQrCodes, totalQrCodes)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 更新任务错误信息
     *
     * @param id       任务ID
     * @param errorMessage 错误信息
     */
    public void updateTaskError(Long id, String errorMessage) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, id)
                .set(SearchTask::getStatus, "FAILED")
                .set(SearchTask::getErrorMessage, errorMessage)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 逻辑删除任务
     *
     * @param id 任务ID
     * @param userId 用户ID
     */
    public void deleteTask(Long id, Long userId) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, id)
                .eq(SearchTask::getUserId, userId)
                .set(SearchTask::getDeleted, 1)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 查询待执行的任务（只返回启用的任务）
     *
     * @return 待执行任务列表
     */
    public List<SearchTask> findPendingTasks() {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getDeleted, 0)
                .eq(SearchTask::getEnabled, 1)  // 只查询启用的任务
                .orderByAsc(SearchTask::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 查询所有启用的任务
     *
     * @return 启用的任务列表
     */
    public List<SearchTask> findEnabledTasks() {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getDeleted, 0)
                .eq(SearchTask::getEnabled, 1)  // 只查询启用的任务
                .orderByAsc(SearchTask::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 更新任务最后执行时间
     *
     * @param taskId 任务ID
     * @param lastExecuteTime 最后执行时间
     */
    public void updateLastExecuteTime(Long taskId, LocalDateTime lastExecuteTime) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, taskId)
                .set(SearchTask::getLastExecuteTime, lastExecuteTime)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 根据用户ID和任务名称查询任务
     *
     * @param userId   用户ID
     * @param taskName 任务名称
     * @return 任务列表
     */
    public List<SearchTask> findByUserIdAndTaskName(Long userId, String taskName) {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getTaskName, taskName)
                .eq(SearchTask::getDeleted, 0)
                .orderByDesc(SearchTask::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 根据用户ID获取任务名称列表
     *
     * @param userId 用户ID
     * @return 任务名称列表
     */
    public List<String> getTaskNamesByUserId(Long userId) {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getDeleted, 0)
                .select(SearchTask::getTaskName)
                .orderByDesc(SearchTask::getCreateTime);
        
        return this.list(queryWrapper).stream()
                .map(SearchTask::getTaskName)
                .distinct()
                .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 根据用户ID获取任务列表（包含ID和名称等信息）
     *
     * @param userId 用户ID
     * @return 任务列表
     */
    public List<TaskListResponse> getTaskListByUserId(Long userId) {
        LambdaQueryWrapper<SearchTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getDeleted, 0)
                .orderByDesc(SearchTask::getCreateTime);
        
        return this.list(queryWrapper).stream()
                .map(task -> new TaskListResponse(
                    task.getId(),
                    task.getTaskName()
                ))
                .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 更新任务关键词
     *
     * @param taskId 任务ID
     * @param keywords 新的关键词
     */
    public void updateTaskKeywords(Long taskId, String keywords) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, taskId)
                .set(SearchTask::getKeywords, keywords)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }

    /**
     * 更新任务
     */
    public void updateTask(Long taskId, String keywords, Integer executeInterval, Integer postTimeLimit, Integer searchPages) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, taskId)
                .set(SearchTask::getKeywords, keywords)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        
        if (executeInterval != null) {
            updateWrapper.set(SearchTask::getExecuteInterval, executeInterval);
        }
        if (postTimeLimit != null) {
            updateWrapper.set(SearchTask::getPostTimeLimit, postTimeLimit);
        }
        if (searchPages != null) {
            updateWrapper.set(SearchTask::getSearchPages, searchPages);
        }
        
        this.update(updateWrapper);
    }

    /**
     * 更新任务（兼容老接口）
     */
    public void updateTask(Long taskId, String keywords, Integer executeInterval, Integer postTimeLimit) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, taskId)
                .set(SearchTask::getKeywords, keywords)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        
        if (executeInterval != null) {
            updateWrapper.set(SearchTask::getExecuteInterval, executeInterval);
        }
        if (postTimeLimit != null) {
            updateWrapper.set(SearchTask::getPostTimeLimit, postTimeLimit);
        }
        
        this.update(updateWrapper);
    }

    /**
     * 更新任务启用状态
     *
     * @param taskId 任务ID
     * @param enabled 是否启用：0-禁用，1-启用
     */
    public void updateTaskEnabled(Long taskId, Integer enabled) {
        LambdaUpdateWrapper<SearchTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SearchTask::getId, taskId)
                .set(SearchTask::getEnabled, enabled)
                .set(SearchTask::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
    }
} 